package com.mushuilingfeng.ddd.user.infrastructure.base;

import cn.hutool.core.collection.CollUtil;
import com.mushuilingfeng.ddd.user.domain.base.BusinessException;
import com.mushuilingfeng.ddd.user.domain.base.VerifyCodeType;
import com.mushuilingfeng.ddd.user.domain.base.service.VerifyCodeService;
import com.mushuilingfeng.ddd.user.infrastructure.verifycode.AbstractVerifyCodeService;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author
 * @date 2024/9/29
 */
@Service
@Primary
public class VerifyCodeServiceImpl implements VerifyCodeService {

    @Resource
    private List<AbstractVerifyCodeService> verifyCodeServices;

    private AbstractVerifyCodeService getVerifyCodeService(VerifyCodeType type) {
        if (CollUtil.isEmpty(verifyCodeServices)) {
            throw new BusinessException(-1, "没有可用的验证码服务");
        }
        return verifyCodeServices.stream().filter(verifyCodeService -> verifyCodeService.canProcess(type)).findFirst().orElseThrow(() -> new BusinessException(-1, "没有可用的验证码服务"));
    }

    @Override
    public void sendVerifyCode(String tel, VerifyCodeType type) {
        getVerifyCodeService(type).sendVerifyCode(tel, type);

    }

    @Override
    public boolean verifyCode(String tel, VerifyCodeType type, String code) {
        return getVerifyCodeService(type).verifyCode(tel, type, code);
    }

}
